package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"users/models"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	const limit = 5
	page, _ := c.GetInt("page", 1)
	var users []models.User
	var total int
	err := models.DB.Limit(limit).Offset((page - 1) * limit).Order("id desc").Find(&users).Error
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "数据库繁忙",
		}
		c.ServeJSON()
		return
	}
	err = models.DB.Model(&models.User{}).Pluck("count(*)", &total).Error
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "数据库繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "查询成功",
		Data: struct {
			Total int
			Users []models.User
		}{
			total,
			users,
		},
	}
	c.ServeJSON()
}
func (c *UserController) Update() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	id, _ := c.GetInt("id")
	if c.Ctx.Input.Method() == "GET" {
		var user models.User
		models.DB.Where("id = ?", id).First(&user)
		c.Data["json"] = models.Msg{
			Code: 200,
			Msg:  "",
			Data: user,
		}
		c.ServeJSON()
		return
	}
	user := models.User{
		Name:  c.GetString("name"),
		Tel:   c.GetString("tel"),
		Level: c.GetString("level"),
		From:  c.GetString("form"),
		Model: gorm.Model{ID: uint(id)},
	}
	err := models.DB.Updates(&user).Error
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "数据库繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "修改成功",
	}
	c.ServeJSON()
}
func (c *UserController) Black() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	id, _ := c.GetInt("id")
	var user models.User
	user.Type = "黑名单"
	user.ID = uint(id)
	err := models.DB.Updates(&user).Error
	if err != nil {
		c.Data["json"] = models.Msg{
			Code: 0,
			Msg:  "数据库繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.Msg{
		Code: 200,
		Msg:  "修改成功",
	}
	c.ServeJSON()
}
